package com.code.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.code.iface.ITree;
import com.code.vo.TreeVO;

public class TreeUtil {
	
	public static String tree(List<? extends ITree> list, boolean isCheckbox) {
		return tree(list, 0l, isCheckbox, null, true);
	}
	
	public static String tree(List<? extends ITree> list, boolean isCheckbox, List<? extends ITree> owns) {
		return tree(list, 0l, isCheckbox, owns, true);
	}
	
	public static String tree(List<? extends ITree> list, boolean isCheckbox, List<? extends ITree> owns, boolean isCurNodeLocation) {
		return tree(list, 0l, isCheckbox, owns, isCurNodeLocation);
	}
	
	public static String tree(List<? extends ITree> list, Long parentId, boolean isCheckbox,  List<? extends ITree> owns, boolean isCurNodeLocation) {
		StringBuffer buffer = new StringBuffer();
		
		Map<Long, TreeVO> map = new HashMap<Long, TreeVO>();
		List<TreeVO> parents = new ArrayList<TreeVO>();
		
		for (ITree tree : list) {
			map.put(tree.getId(), new TreeVO(tree));
			
			if (null == tree.getParentId() || parentId.equals(tree.getParentId())) {
				parents.add(new TreeVO(tree));
			}
		}
		
		for (ITree tree : list) {
			if (null == tree.getParentId() || parentId == tree.getParentId())
				continue;
			
			if (map.containsKey(tree.getParentId()) && map.containsKey(tree.getId())) {
				TreeVO parent = map.get(tree.getParentId());
				parent.getChildren().add(map.get(tree.getId()));
			}
		}
		
		for (TreeVO tree : parents) {
			tree = map.get(tree.getId());
			buffer.append(iterator(tree, isCheckbox, owns, isCurNodeLocation));
		}
		
		return ("[" + buffer.toString() + "]").replace(",]", "]");
	}
	
	private static String iterator(TreeVO parent, boolean isCheckbox, List<? extends ITree> owns, boolean isCurNodeLocation) {
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("{text:'" + parent.getText() + "',id:" + parent.getId() + ",attr:" + parent.getAttrJson() + ",");
		if (isCheckbox) {
			if (null != owns) {
				boolean flag = false;
				for (ITree own : owns) {
					Long temp = 0L;
					if (isCurNodeLocation) {
						temp = own.getId();
					} else {
						temp = own.getParentId();
					}
					
					if (temp.equals(parent.getId())) {
						flag = true;
						break;
					}
				}
				
				if (flag) {
					buffer.append("checked:true,");
				} else {
					buffer.append("checked:false,");
				}
				
				
			} else {
				buffer.append("checked:false,");
			}
			
		}
		
		if (parent.getLeaf()) {
			buffer.append("leaf:true,cls:'file'");
		} else {
			buffer.append("cls:'folder',children:[");
			
			for (TreeVO child : parent.getChildren()) {
				buffer.append(iterator(child, isCheckbox, owns, isCurNodeLocation));
			}
			
			buffer.append("]");
		}
		buffer.append("},");
		
		return buffer.toString();
	}
	
}
